package com.mccree.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * 自定义服务器handler
 * @author zhabo
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int length = msg.getLength();
        byte[] data = msg.getData();

        System.out.println("服务器接收到的信息如下:");
        System.out.println("长度:"+length);
        System.out.println("内容:"+new String(data, StandardCharsets.UTF_8));
        System.out.println("服务器接收到的数据量:"+(++this.count));
        System.out.println("\n\n\n-------------------------------");


        //回复消息
        byte[] bytes = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
        int length1 = bytes.length;
        //封装协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLength(length1);
        messageProtocol.setData(bytes);
        ctx.writeAndFlush(messageProtocol);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}
